<?php

namespace App\Http\Controllers\Backend\Auth;

use App\Entities\Auth\Role;
use App\Http\Controllers\Backend\Controller;
use App\Services\Auth\RoleService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

class RoleController extends Controller
{
    protected $services;

    public function __construct(RoleService $service)
    {
        $this->service = $service;
        $this->baseViewAddress = 'backend.auth.role.';
    }

    public function list()
    {
        return response()->json($this->service->getPageList());
    }

    public function index()
    {
        return View::make($this->baseViewAddress.'index');
    }

    public function create()
    {
        $role = new Role();

        return View::make($this->baseViewAddress.'create', compact('role'));
    }

    public function store(Request $request)
    {
        if ($this->service->create($request->all())) {
            return redirect(route('admin.auth.role.index'))->with(['status' => '添加成功']);
        }

        return redirect(route('admin.auth.role.index'))->with(['status' => '系统错误']);
    }

    public function show($id)
    {
        $role = $this->service->show($id);

        return  View::make($this->baseViewAddress.'show', compact('role'));
    }

    public function edit($id)
    {
        $role = $this->service->show($id);

        return  View::make($this->baseViewAddress.'edit', compact('role'));
    }

    public function update(Request $request, $id)
    {
        if ($this->service->update($id, $request->all())) {
            return redirect(route('admin.auth.role.index'))->with(['status' => '更新成功']);
        }

        return redirect(route('admin.auth.role.index'))->withErrors(['status' => '系统错误']);
    }

    public function destroy()
    {
        $ids = request()->get('ids');

        if (empty($ids)) {
            return response()->json(['code' => 1, 'msg' => '请选择删除项']);
        }
        $result = $this->service->remove($ids);
        if ($result['flag']) {
            return response()->json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return response()->json(['code' => 1, 'msg' => $result['message'] ? $result['message'] : '系统错误']);
        }
    }

    public function permission($id)
    {
        return  View::make($this->baseViewAddress.'permission', compact('id'));
    }

    public function getModules($id)
    {
        $data = $this->service->getModules($id);

        return response()->json($data);
    }

    public function savePermission($id, Request $request)
    {
        $modules = $request->get('modules');
        $modules = explode(',', $modules);
        if ($this->service->savePermission($id, $modules)) {
            return redirect(route('admin.auth.role.index'))->with(['status' => '分配成功']);
        }

        return redirect(route('admin.auth.role.index'))->withErrors(['status' => '系统错误']);
    }
}
